<?php
/**
 * @api {get} /Api/Order/collectList Request 收藏列表
 * @apiName goodsList
 * @apiGroup Order
 *
 * @apiSuccess {Number}  user_id 用户id.
 */
/**
 * @api {get} /Api/Order/collectAdd Request 点击收藏
 * @apiName collectAdd
 * @apiGroup Order
 *
 * @apiParam {Number}  user_id 用户id.
 * @apiParam {Number}  goods_id 商品id.
 */
/**
 * @api {get} /Api/Order/collectDel Request 删除收藏 批量删除 2-2-2 id通过-相连
 * @apiName collectDel
 * @apiGroup Order
 *
 * @apiParam {Number}  collect_id 商品id.
 */
/**
 * @api {get} /Api/Order/cartList Request 购物车列表
 * @apiName cartList
 * @apiGroup Order
 *
 * @apiParam {Number}  user_id 用户id.
 */
/**
 * @api {get} /Api/Order/cartAdd Request 添加购物车
 * @apiName cartAdd
 * @apiGroup Order
 *
 * @apiParam {Number}  user_id 用户id.
 * @apiParam {Number}  goods_id 商品id.
 * @apiParam {Number}  goods_num 商品数量.
 * @apiParam {Number}  item_id 商品规格id.
 * @apiParam {Number}  type 1增加商品数量 2减少数量 3更改选中状态.
 */
/**
 * @api {get} /Api/Order/cartDel Request 删除购物车
 * @apiName cartDel
 * @apiGroup Order
 *
 * @apiParam {Number}  cartid 购物车id.
 */
/**
 * @api {get} /Api/Order/orderAdd Request 生成订单
 * @apiName orderAdd
 * @apiGroup Order
 *
 * @apiParam {Number}  address_id 地址address_id.
 * @apiParam {String}  cart_id 8-8-8cart_id购物车通过-连接.
 * @apiParam {Number}  user_id 用户id.
 * @apiParam {String}  message 留言.
 * @apiParam {Number}  paytype 支付方式 zfbpay支付宝支付，wxpay微信支付，ylpay银联支付，qbpay钱包.
 */
/**
 * @api {get} /Api/Order/orderList Request 订单列表
 * @apiName orderList
 * @apiGroup Order
 *
 * @apiParam {Number}  user_id 用户id.
 * @apiParam {Number}  pay_status 支付状态 0 未支付  1已支付.
 */
namespace app\api\controller;
use app\common\controller\Api;
use app\common\logic\GoodsLogic;
use \think\Log;
use think\Session;
use app\common\logic\CartLogic;
use think\Db;
class Order extends Api
{
    public function _initialize(){ // 如果子类存在initialize,则不执行父类的内容
//        Session::set('userid','8');
        $userid = Session::get('userid');
//        if ($userid <= 0 || $userid == ''){
//            echo json_encode(codemsg(-4010));die;
//        }
    }
    //收藏列表
    public function collectList(){
        //获取用户id
        $result = $this->request->param();
        $userid = $result['user_id'];
        if ($userid <=0){
            echo json_encode(codemsg(-1));die;
        }
        //获取用户收藏列表
        $data = model('Collect')->collectList(0,$userid,0);
        $return = codemsg(5003);
        $return['data'] = $data;
        echo json_encode($return);die;
    }
    //点击收藏
    public function collectAdd(){
//        if($this->request->isPOST){
            $result = $this->request->param();
            $goods_id = $result['goods_id'];
            $userid = $result['user_id'];
            if ($userid <=0){
                echo json_encode(codemsg(-1));die;
            }
            if ($goods_id <=0){
                echo json_encode(codemsg(-1));die;
            }
            //判断该商品用户已经收藏
            $is_collect = model('Collect')->collectFind($goods_id,$userid);
            if (!empty($is_collect)){
                //用户该商品已经收藏
                echo json_encode(codemsg(-6000));die;
            }
            //判断是否存在该商品
            $is_goods = model('Goods')->goodsFind($goods_id);
            if (empty($is_goods) || $is_goods == false){
                //该商品不存在
                echo json_encode(codemsg(-6001));die;
            }
            //添加收藏
            $data = model('Collect')->collectAdd($goods_id,$userid);
            if ($data){
                echo json_encode(codemsg(3));die;
            }else{
                echo json_encode(codemsg(-4));die;
            }
//        }else{
//            $return = codemsg(-7);
//            Log::faceapi('【Face/index】-[return]--'.json_encode($return));
//            echo json_encode($return);die;
//        }
    }
    //删除收藏
    public function collectDel(){
//        if($this->request->isPOST){
            $result = $this->request->param();
            $collect_id = $result['collect_id'];
            if (empty($collect_id)){
                echo json_encode(codemsg(-1));die;
            }
            //删除收藏
            $idlist = explode('-',$collect_id);
            $where['collect_id'] = array('in',$idlist);
            $data = M('goods_collect')->where($where)->delete();
            if ($data){
                echo json_encode(codemsg(3));die;
            }else{
                echo json_encode(codemsg(-4));die;
            }
//        }else{
//            $return = codemsg(-7);
//            Log::faceapi('【Face/index】-[return]--'.json_encode($return));
//            echo json_encode($return);die;
//        }
    }
    //购物车列表
    public function cartList(){
        $result = $this->request->param();
        $userid = $result['user_id'];
        if ($userid <=0){
            echo json_encode(codemsg(-1));die;
        }
        $cartLogic = new CartLogic();
        $cartLogic->setUserId($userid);
        $cartList = $cartLogic->getCartList();//用户购物车
        $userCartGoodsTypeNum = $cartLogic->getUserCartGoodsTypeNum();//获取用户购物车商品总数
        $cartList = collection($cartList)->toArray();
        $data['data']['cartList'] = $cartList;
        $data['data']['userCartGoodsTypeNum'] = $userCartGoodsTypeNum;
        $return = codemsg(5003);
        $return['data'] = $data;
        echo json_encode($return);die;
    }
    //添加购物车
    public function cartAdd(){
        $goods_id = I("goods_id/d"); // 商品id
        $goods_num = I("goods_num/d");// 商品数量
        $item_id = I("item_id/d"); // 商品规格id
        $type = I("type/d"); // 1操作 增加商品数量 2减少数量 3更改选中状态
        $userid = I("user_id/d"); // 用户id
//        $goods_id = 114;
//        $goods_num = 2;
//        $type = 1;
//        $item_id = 126;
//        $userid = 13;

        if (empty($goods_id)) {
            //商品id为空
            $return = codemsg(-6002);
            echo json_encode($return);die;
        }
        if (empty($goods_num)) {
            //购买商品数量小于0
            $return = codemsg(-6003);
            echo json_encode($return);die;
        }
        if ($userid <=0){
            echo json_encode(codemsg(-1));die;
        }
        //查询是否存在该购物车记录
        $cartFind['goods_id'] = $goods_id;
        $cartFind['item_id'] = $item_id;
        $cartFind['user_id'] = $userid;
        $cartFinddata = model('Cart')->cartFind($cartFind);
        if ($cartFinddata){
            $editdata['goods_id'] = $cartFind['goods_id'];
            $editdata['spec_key'] = $cartFind['item_id'];
            $editdata['goods_num'] = $goods_num;
            $editdata['cart_num'] = $cartFinddata['goods_num'];
            $editdata['cartid'] = $cartFinddata['id'];
            $editdata['type'] = $type;
            $edit = $this->cartEdit($editdata);die;
        }
        $cartLogic = new CartLogic();
        //获取该商品
        $Goods = new \app\common\model\Goods();
        $goods = $Goods::get($goods_id);
        $goods = $goods->toArray();
        if (empty($goods) || ($goods['is_on_sale'] == 0)) {
            //商品已经下架
            $data = codemsg(-5002);
            echo json_encode($data);die;
        }
        //查找产品规格尺码等
        $spec_goods_price = M('spec_goods_price')->where("goods_id", $goods_id)->getField("key,item_id,price,store_count,market_price"); // 规格 对应 价格 库存表
        $catrtype = $cartLogic->setSpecGoodsPriceByIdApi($item_id)->toArray();
        if (empty($spec_goods_price[$catrtype['key']]) ||$spec_goods_price[$catrtype['key']] == ''){
            //不存在该规格产品
            $return = codemsg(-6004);
            echo json_encode($return);die;
        }
        if ($spec_goods_price[$catrtype['key']]['store_count'] < $goods_num){
            //加入购物车的商品超过库存
            $return = codemsg(-6005);
            echo json_encode($return);die;
        }
        $cart['user_id'] = $userid;
        session_start();
        $cart['session_id'] = session_id();
        $cart['goods_id'] = $goods['goods_id'];
        $cart['goods_sn'] = $goods['goods_sn'];
        $cart['goods_name'] = $goods['goods_name'];
        $cart['market_price'] = $goods['market_price'];
        $cart['goods_price'] = $goods['shop_price'];
        $cart['member_goods_price'] = $goods['cost_price'];
        $cart['goods_num'] = $goods_num;
        $cart['item_id'] = $catrtype['item_id'];
        $cart['spec_key'] = $catrtype['key'];
        $cart['spec_key_name'] = $catrtype['key_name'];
        $cart['bar_code'] = $catrtype['bar_code'];
        $cartAdd = model('Cart')->cartAdd($cart);
        if ($cartAdd){
            //新增购物车成功
            $return = codemsg(3);
            echo json_encode($return);die;
        }else{
            //新增购物车失败
            $return = codemsg(-4);
            echo json_encode($return);die;
        }

    }
    //追加购物车数量/选中状态
    public function cartEdit($data=0){
        if ($data==0){
//            if($this->request->isPOST){
                $result = $this->request->param();
                $data['type'] = $result["type"]; //操作类型 1操作商品数量 2减少数量 3更改选中状态
                $data['selected'] = $result["selected"]; // 是否选中
                if ($data['type'] !=1 && $data['type'] != 2 && $data['type'] !=3) {
                    $return = codemsg(-9);
                    echo json_encode($return);die;
                }
//            }else{
//                $return = codemsg(-7);
//                Log::faceapi('【Face/index】-[return]--'.json_encode($return));
//                echo json_encode($return);die;
//            }
        }
        if ($data['type'] !=1 && $data['type'] != 2 && $data['type'] != 3){
            //参数错误
            $return = codemsg(-9);
            echo json_encode($return);die;
        }
        //操作商品数量
        if ($data['type']==1 || $data['type']==2){
            if ($data['goods_num'] <= 0){
                //数量错误
                $return = codemsg(-6003);
                echo json_encode($return);die;
            }
            if ($data['spec_key'] <= 0){
                $return = codemsg(-6004);
                echo json_encode($return);die;
            }
            //对订单进行操作
            if ($data['type'] == 2){
                $num = $data['cart_num'] - $data['goods_num'];
                if ($num<=1){
                    //操作数量错误
                    $return = codemsg(-6006);
                    echo json_encode($return);die;
                }
            }
            //判断库存是否够
            if ($data['type'] == 1){
                $num = $data['cart_num'] + $data['goods_num'];
                $cartLogic = new CartLogic();
                $spec_goods_price = M('spec_goods_price')->where("goods_id", $data['goods_id'])->getField("key,item_id,price,store_count,market_price"); // 规格 对应 价格 库存表
                $catrtype = $cartLogic->setSpecGoodsPriceByIdApi($data['spec_key'])->toArray();
                if ($spec_goods_price[$catrtype['key']]['store_count'] < $data['goods_num']){
                    //加入购物车的商品超过库存
                    $return = codemsg(-6005);
                    echo json_encode($return);die;
                }
            }
            $cart['num'] = $num;
            $cart['cart_id'] = $data['cartid'];
            //修改数量
            $cartEdit = model('Cart')->cartEdit($cart);
            if ($cartEdit){
                //成功
                $return = codemsg(3);
                echo json_encode($return);die;
            }else{
                //失败
                $return = codemsg(-4);
                echo json_encode($return);die;
            }
        }else{
            //操作选中状态
            if ($data['selected'] !=0 && $data['selected'] != 1){
                //操作错误
                $return = codemsg(-4);
                echo json_encode($return);die;
            }
            $cart['cart_id'] = $data['cartid'];
            $cart['selected'] = $data['selected'];
            $cartEdit = model('Cart')->cartEdit($cart);
            if ($cartEdit){
                //成功
                $return = codemsg(3);
                echo json_encode($return);die;
            }else{
                //失败
                $return = codemsg(-4);
                echo json_encode($return);die;
            }
        }
    }
    //删除购物车
    public function cartDel(){
//        if($this->request->isPOST){
            $result = $this->request->param();
            if ($result['cartid'] <=0 || empty($result['cartid'])){
                //参数错误
                $return = codemsg(-9);
                echo json_encode($return);die;
            }
            $cart = array();
            $cart['cartid'] = $result['cartid'];
            $cartdel = model('Cart')->cartDel($cart);
            if ($cartdel){
                //操作成功
                $return = codemsg(3);
                echo json_encode($return);die;
            }else{
                //操作失败
                $return = codemsg(-4);
                echo json_encode($return);die;
            }
//        }else{
//            $return = codemsg(-7);
//            Log::faceapi('【Face/index】-[return]--'.json_encode($return));
//            echo json_encode($return);die;
//        }
    }
    //生成订单 地址address_id 购物车 8-8-8 cart_id购物车通过-连接 user_id用户id ，paytype 支付方式 zfbpay支付宝支付，wxpay微信支付，ylpay银联支付，qbpay钱包
    public function orderAdd(){
        $address = I('post.address_id');
        $cart = I('post.cart_id');
        $user_id = I('post.user_id');
        $paytype = I('post.paytype');
        $message = I('post.message');
        Log::api('【Order/orderAdd】-[参数]--'.json_encode($address."**".$cart."**".$user_id."**".$paytype.$message));

        //地址id
        if ($address <= 0 || empty($address)){
            $return = codemsg(-7024);
            echo json_encode($return);die;
        }
        //购物车id
        if (empty($cart)){
            $return = codemsg(-7023);
            echo json_encode($return);die;
        }
        //用户id
        //订单生成
        if (empty($user_id)){
            $return = codemsg(-3);
            echo json_encode($return);die;
        }
        $paytool = array(
          'zfbpay'=>'支付宝支付',
          'wxpay'=>'微信支付',
          'ylpay'=>'银联支付',
          'qbpay'=>'钱包支付'
        );
        if (in_array($paytype,$paytool)){
            $return = codemsg(-3);
            echo json_encode($return);die;
        }
        //查询该用户
        $whereusera['user_id'] = array('eq',$user_id);
        $whereusera['is_lock'] = array('eq',0);
        $user = M('users')->where($whereusera)->find();
        //查询地址
        $whereuser['address_id'] = array('eq',$address);
        $whereuser['is_del'] = array('eq',0);
        $user_address = M('user_address')->where($whereuser)->find();
        Db::startTrans();
        try{
            //购物车
            $cart = $this->catrDel($cart);
            if ($cart['code'] <= 0){
                echo json_encode($cart);die;
            }
            //生成订单
              //生成订单号
              $map['order_sn'] = $this->createOrderNm();
              $map['user_id'] = $user_id;
              $map['consignee'] = $user_address['consignee'];
              $map['province'] = $user_address['province'];
              $map['city'] = $user_address['city'];
              $map['district'] = $user_address['district'];
              $map['twon'] = $user_address['twon'];
              $map['address'] = $user_address['address'];
              $map['zipcode'] = $user_address['zipcode'];
              $map['mobile'] = $user_address['mobile'];
              $map['email'] = $user_address['email'];
              //支付企业类别
              $map['pay_code'] = $paytype;
              $map['pay_name'] = $paytool[$paytype];
              //商品总价
              $map['goods_price'] = $cart['num'];
              $map['order_amount'] = $cart['num'];
              $map['total_amount'] = $cart['num'];
              if ($message){
                  $map['message'] = $message;
              }
              $map['add_time'] = time();
              //新增订单 获取订单id
              $orderAdd = M('order')->insertGetId($map);
              foreach ($cart['data'] as $k=>$v){
                  $v['order_id'] = $orderAdd;
                  $a = '';
                  $a = M('order_goods')->insertGetId($v);
                  if ($a > 0){
                    //删除购物车
                    $where = array();
                    $where['goods_id'] = array('eq',$v['goods_id']);
                    $where['spec_key'] = array('eq',$v['spec_key']);
                    $del = M('cart')->where($where)->delete();
                  }else{
                      $return = codemsg(-7007);
                      Log::api('【Order/orderAdd】-[返回]--'.json_encode($return));
                      echo json_encode($return);die;
                  }
              }
              //新增订单到订单商品详情
//            // 提交事务
            Db::commit();
            $return = codemsg(3);
            echo json_encode($return);die;
        } catch (\Exception $e) {
            // 回滚事务
            //记录错误日志
            Db::rollback();
            //返回错误
            $return = codemsg(-7007);
            Log::api('【Order/orderAdd】-[返回]--'.json_encode($return));
            echo json_encode($return);die;
        }
    }
    //订单列表 pay_status =0 未支付 1 已支付
    public function orderList(){
        //获取用户id
        $user_id = I('user_id');
        $pay_status = I('pay_status');
        if (empty($user_id)){
            $return = codemsg(-3);
            echo json_encode($return);die;
        }
        if ($pay_status==0){
            //未支付
            $where['o.pay_status'] = array('eq',0);
            $where['o.order_status'] = array('eq',0);
        }else{
            //已支付
            $where['o.pay_status'] = array('eq',1);
            $where['o.order_status'] = array('eq',1);
        }
        //多表联查出
        $where['o.user_id'] = array('eq',$user_id);
        $data = M('order')
                ->alias('o')
                ->field('o.*,g.original_img,og.goods_id')
                ->join('order_goods og','og.order_id=o.order_id')
                ->join('goods g','og.goods_id=g.goods_id')
                ->where($where)
                ->order('o.order_id desc')
                ->select();
        $list = array();
        if ($data){
            foreach ($data as $k=>$v){
                foreach ($data as $kk=>$vv){
                    if ($v['order_id'] == $vv['order_id']){
                        $list[$v['order_id']][] = $vv;
                        break;
                    }
                }
            }
        }
        if ($list){
            $return = codemsg(5003);
            Log::api('【Order/orderList】-[返回]--'.json_encode($return));
            echo json_encode($return);die;
        }else{
            $return = codemsg(-7028);
            Log::api('【Order/orderList】-[返回]--'.json_encode($return));
            echo json_encode($return);die;
        }
    }
    //添加订单商品到order_goods中
    private function catrDel($cart){
        //拆分list
        $cartlist = explode('-',$cart);
        $where['id'] = array('in',$cartlist);
        //获取所有的购物车列表
        $list = M('cart')->where($where)->select();
        if (empty($list)){
            $return = codemsg(-7029);
            Log::api('【Order/catrDel】-[返回]--'.json_encode($return));
            return $return;
        }
        $data = array();
        $num = 0;
        foreach ($list as $k => $v){
            $cartLogic = new CartLogic();
            $spec_goods_price = M('spec_goods_price')->where("goods_id", $v['goods_id'])->getField("key,item_id,price,store_count,market_price"); // 规格 对应 价格 库存表
            $catrtype = $cartLogic->setSpecGoodsPriceByIdApi($v['item_id'])->toArray();
            if ($spec_goods_price[$catrtype['key']]['store_count'] < $data['goods_num']){
                //加入购物车的商品超过库存
                $code['code'] = '-7026';
                $code['msg'] = '商品“'.$v['goods_name'].'”库存不足';
                $return = $code;
                return $return;
            }
            $num+=$v['goods_num']*$v['goods_price'];
            $data[$k]['goods_id'] = $v['goods_id'];
            $data[$k]['goods_name'] = $v['goods_name'];
            $data[$k]['goods_sn'] = $v['goods_sn'];
            $data[$k]['goods_num'] = $v['goods_num'];
            $data[$k]['final_price'] = $v['goods_price'];
            $data[$k]['goods_price'] = $v['goods_price'];
            $data[$k]['cost_price'] = $v['goods_price'];
            $data[$k]['member_goods_price'] = $v['member_goods_price'];
            $data[$k]['give_integral'] = 0;
            $data[$k]['spec_key'] = $v['spec_key'];
            $data[$k]['spec_key_name'] = $v['spec_key_name'];
            $data[$k]['bar_code'] = $v['bar_code'];
        }
        $return['data'] = $data;
        $return['num'] = $num;
        $return['code'] = 1;
//        $del = M('cart')->where($where)->delete();
        return $return;
    }
    /**
     * 生成15位的订单号
     * @return string 订单号
     */
    public function createOrderNm()
    {
        $year_code = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
        $date_code = array('0',
            '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
            'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M',
            'N', 'O', 'P', 'Q', 'R', 'T', 'U', 'V', 'W', 'X', 'Y');
        //一共15位订单号,同一秒内重复概率1/10000000,26年一次的循环\
        $order_sn = $year_code[(intval(date('Y')) - 2010) % 26] . //年 1位
            strtoupper(dechex(date('m'))) . //月(16进制) 1位
            $date_code[intval(date('d'))] . //日 1位
            substr(time(), -5) . substr(microtime(), 2, 5) . //秒 5位 // 微秒 5位
            sprintf('%02d', rand(0, 99)); //  随机数 2位
        return ZH.$order_sn;
    }
}